/**
 * 单元测试覆盖率分析器
 * 分析源代码和生成的测试用例，预估行覆盖率和分支覆盖率
 */

import * as fs from 'fs';
import * as path from 'path';
import { Logger } from '../../../src/logger/Logger';

export interface CoverageReport {
    functionName: string;
    sourceFile: string;
    
    // 行覆盖率
    totalLines: number;           // 总可执行行数
    coveredLines: number;         // 预计覆盖的行数
    lineCoverage: number;         // 行覆盖率百分比
    
    // 分支覆盖率
    totalBranches: number;        // 总分支数
    coveredBranches: number;      // 预计覆盖的分支数
    branchCoverage: number;       // 分支覆�erage百分比
    
    // 详细信息
    branches: BranchInfo[];       // 分支详情
    uncoveredScenarios: string[]; // 未覆盖的场景
    testCases: TestCaseInfo[];    // 测试用例信息
}

export interface BranchInfo {
    type: 'if' | 'else' | 'switch' | 'case' | 'for' | 'while' | 'ternary' | 'logical';
    location: string;             // 位置描述
    covered: boolean;             // 是否被覆盖
    condition?: string;           // 条件表达式
}

export interface TestCaseInfo {
    name: string;                 // 测试用例名称
    scenario: string;             // 测试场景描述
    expectedBranches: string[];   // 预计覆盖的分支
}

export class CoverageAnalyzer {
    
    /**
     * 分析整个文件的覆盖率预期（新方法）
     */
    public static async analyzeFileCoverage(
        sourceCode: string,
        displayName: string,
        testCode: string,
        sourceFile: string
    ): Promise<CoverageReport> {
        
        Logger.info(`[CoverageAnalyzer] 🔍 分析文件覆盖率: ${displayName}`);
        Logger.info(`[CoverageAnalyzer]    源代码长度: ${sourceCode.length} 字符`);
        Logger.info(`[CoverageAnalyzer]    测试代码长度: ${testCode.length} 字符`);
        
        // 直接使用整个源代码作为分析对象
        const codeToAnalyze = sourceCode;
        
        // 2. 分析可执行行
        const executableLines = this.analyzeExecutableLines(codeToAnalyze);
        Logger.info(`[CoverageAnalyzer]    可执行行数: ${executableLines}`);
        
        // 3. 分析分支
        const branches = this.analyzeBranches(codeToAnalyze);
        Logger.info(`[CoverageAnalyzer]    分支数量: ${branches.length}`);
        
        // 4. 分析测试用例
        const testCases = this.analyzeTestCases(testCode, '');  // 空字符串表示不限定函数名
        Logger.info(`[CoverageAnalyzer]    测试用例数: ${testCases.length}`);
        
        // 5. 评估覆盖情况
        const coverage = this.estimateCoverage(codeToAnalyze, branches, testCases);
        
        // 6. 识别未覆盖的场景
        const uncoveredScenarios = this.identifyUncoveredScenarios(branches, testCases);
        
        const lineCoverage = executableLines > 0 ? (coverage.coveredLines / executableLines) * 100 : 0;
        const branchCoverage = branches.length > 0 ? (coverage.coveredBranches / branches.length) * 100 : 0;
        
        Logger.info(`[CoverageAnalyzer] 📊 覆盖率预估:`);
        Logger.info(`[CoverageAnalyzer]    行覆盖: ${coverage.coveredLines}/${executableLines} (${lineCoverage.toFixed(1)}%)`);
        Logger.info(`[CoverageAnalyzer]    分支覆盖: ${coverage.coveredBranches}/${branches.length} (${branchCoverage.toFixed(1)}%)`);
        
        return {
            functionName: displayName,
            sourceFile,
            totalLines: executableLines,
            coveredLines: coverage.coveredLines,
            lineCoverage,
            totalBranches: branches.length,
            coveredBranches: coverage.coveredBranches,
            branchCoverage,
            branches,
            uncoveredScenarios,
            testCases
        };
    }
    
    /**
     * 分析函数的覆盖率预期（保留原方法）
     */
    public static async analyzeFunctionCoverage(
        sourceCode: string,
        functionName: string,
        testCode: string,
        sourceFile: string
    ): Promise<CoverageReport> {
        
        Logger.info(`[CoverageAnalyzer] 🔍 分析函数覆盖率: ${functionName}`);
        
        // 1. 提取函数体
        const functionBody = this.extractFunctionBody(sourceCode, functionName);
        if (!functionBody) {
            Logger.warn(`[CoverageAnalyzer] ⚠️ 未找到函数: ${functionName}，尝试分析整个文件`);
            // 如果找不到函数，直接分析整个源代码
            return this.analyzeFileCoverage(sourceCode, functionName, testCode, sourceFile);
        }
        
        // 2. 分析可执行行
        const executableLines = this.analyzeExecutableLines(functionBody);
        
        // 3. 分析分支
        const branches = this.analyzeBranches(functionBody);
        
        // 4. 分析测试用例
        const testCases = this.analyzeTestCases(testCode, functionName);
        
        // 5. 评估覆盖情况
        const coverage = this.estimateCoverage(functionBody, branches, testCases);
        
        // 6. 识别未覆盖的场景
        const uncoveredScenarios = this.identifyUncoveredScenarios(branches, testCases);
        
        const lineCoverage = executableLines > 0 ? (coverage.coveredLines / executableLines) * 100 : 0;
        const branchCoverage = branches.length > 0 ? (coverage.coveredBranches / branches.length) * 100 : 0;
        
        Logger.info(`[CoverageAnalyzer] 📊 覆盖率预估:`);
        Logger.info(`[CoverageAnalyzer]    行覆盖: ${coverage.coveredLines}/${executableLines} (${lineCoverage.toFixed(1)}%)`);
        Logger.info(`[CoverageAnalyzer]    分支覆盖: ${coverage.coveredBranches}/${branches.length} (${branchCoverage.toFixed(1)}%)`);
        
        return {
            functionName,
            sourceFile,
            totalLines: executableLines,
            coveredLines: coverage.coveredLines,
            lineCoverage,
            totalBranches: branches.length,
            coveredBranches: coverage.coveredBranches,
            branchCoverage,
            branches,
            uncoveredScenarios,
            testCases
        };
    }
    
    /**
     * 提取函数体
     */
    private static extractFunctionBody(sourceCode: string, functionName: string): string | null {
        // 匹配函数定义（支持多种C++函数声明格式）
        const patterns = [
            // 普通函数: ReturnType FunctionName(...) { ... }
            new RegExp(`\\w+\\s+${functionName}\\s*\\([^)]*\\)\\s*\\{`, 'g'),
            // 类成员函数: ReturnType ClassName::FunctionName(...) { ... }
            new RegExp(`\\w+\\s+\\w+::${functionName}\\s*\\([^)]*\\)\\s*\\{`, 'g'),
            // 带const/override等修饰符
            new RegExp(`\\w+\\s+\\w*::?${functionName}\\s*\\([^)]*\\)\\s*(?:const)?\\s*(?:override)?\\s*\\{`, 'g')
        ];
        
        for (const pattern of patterns) {
            const match = pattern.exec(sourceCode);
            if (match) {
                const startIndex = match.index + match[0].length - 1; // { 的位置
                const body = this.extractBlockContent(sourceCode, startIndex);
                if (body) {
                    return body;
                }
            }
        }
        
        return null;
    }
    
    /**
     * 提取大括号块内容
     */
    private static extractBlockContent(code: string, startBrace: number): string | null {
        let depth = 1;
        let i = startBrace + 1;
        
        while (i < code.length && depth > 0) {
            if (code[i] === '{') depth++;
            if (code[i] === '}') depth--;
            i++;
        }
        
        if (depth === 0) {
            return code.substring(startBrace + 1, i - 1);
        }
        
        return null;
    }
    
    /**
     * 分析可执行行数
     */
    private static analyzeExecutableLines(functionBody: string): number {
        const lines = functionBody.split('\n');
        let executableLines = 0;
        
        for (const line of lines) {
            const trimmed = line.trim();
            
            // 跳过空行、注释行、单独的大括号
            if (!trimmed || 
                trimmed.startsWith('//') || 
                trimmed.startsWith('/*') || 
                trimmed.startsWith('*') ||
                trimmed === '{' ||
                trimmed === '}') {
                continue;
            }
            
            // 计算可执行语句（包含分号、return、break、continue等）
            if (trimmed.includes(';') || 
                trimmed.startsWith('return') ||
                trimmed.startsWith('break') ||
                trimmed.startsWith('continue') ||
                trimmed.includes('LOG_') ||
                trimmed.includes('CHECK_') ||
                trimmed.includes('ASSERT_')) {
                executableLines++;
            }
        }
        
        return executableLines;
    }
    
    /**
     * 分析分支
     */
    private static analyzeBranches(functionBody: string): BranchInfo[] {
        const branches: BranchInfo[] = [];
        const lines = functionBody.split('\n');
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            const lineNum = i + 1;
            
            // if 语句
            if (line.startsWith('if')) {
                const condition = this.extractCondition(line, 'if');
                branches.push({
                    type: 'if',
                    location: `Line ${lineNum}`,
                    covered: false,
                    condition
                });
                
                // 如果有else，也算一个分支
                const elseLineIndex = this.findCorrespondingElse(lines, i);
                if (elseLineIndex >= 0) {
                    branches.push({
                        type: 'else',
                        location: `Line ${elseLineIndex + 1}`,
                        covered: false
                    });
                }
            }
            
            // switch 语句
            if (line.includes('switch')) {
                const condition = this.extractCondition(line, 'switch');
                const cases = this.findSwitchCases(lines, i);
                
                for (const caseInfo of cases) {
                    branches.push({
                        type: 'case',
                        location: `Line ${caseInfo.line}`,
                        covered: false,
                        condition: caseInfo.value
                    });
                }
            }
            
            // 三元运算符
            if (line.includes('?') && line.includes(':')) {
                branches.push({
                    type: 'ternary',
                    location: `Line ${lineNum}`,
                    covered: false,
                    condition: line
                });
            }
            
            // 逻辑与/或（可能产生短路分支）
            if ((line.includes('&&') || line.includes('||')) && 
                (line.startsWith('if') || line.startsWith('while') || line.includes('return'))) {
                branches.push({
                    type: 'logical',
                    location: `Line ${lineNum}`,
                    covered: false,
                    condition: line
                });
            }
            
            // 循环（for, while）
            if (line.startsWith('for') || line.startsWith('while')) {
                const loopType = line.startsWith('for') ? 'for' : 'while';
                branches.push({
                    type: loopType as any,
                    location: `Line ${lineNum}`,
                    covered: false,
                    condition: this.extractCondition(line, loopType)
                });
            }
        }
        
        return branches;
    }
    
    /**
     * 提取条件表达式
     */
    private static extractCondition(line: string, keyword: string): string {
        const regex = new RegExp(`${keyword}\\s*\\(([^)]*)\\)`);
        const match = line.match(regex);
        return match ? match[1].trim() : '';
    }
    
    /**
     * 查找对应的else
     */
    private static findCorrespondingElse(lines: string[], ifLineIndex: number): number {
        let depth = 0;
        
        for (let i = ifLineIndex; i < lines.length; i++) {
            const line = lines[i].trim();
            
            if (line.includes('{')) depth++;
            if (line.includes('}')) depth--;
            
            if (depth === 0 && line.startsWith('else')) {
                return i;
            }
        }
        
        return -1;
    }
    
    /**
     * 查找switch的所有case
     */
    private static findSwitchCases(lines: string[], switchLineIndex: number): Array<{line: number, value: string}> {
        const cases: Array<{line: number, value: string}> = [];
        let inSwitch = false;
        let depth = 0;
        
        for (let i = switchLineIndex; i < lines.length; i++) {
            const line = lines[i].trim();
            
            if (line.includes('{')) {
                depth++;
                inSwitch = true;
            }
            if (line.includes('}')) {
                depth--;
                if (depth === 0) break;
            }
            
            if (inSwitch && line.startsWith('case')) {
                const caseValue = line.replace('case', '').replace(':', '').trim();
                cases.push({
                    line: i + 1,
                    value: caseValue
                });
            }
        }
        
        return cases;
    }
    
    /**
     * 分析测试用例
     */
    private static analyzeTestCases(testCode: string, functionName: string): TestCaseInfo[] {
        const testCases: TestCaseInfo[] = [];
        
        Logger.info(`[CoverageAnalyzer]    开始分析测试用例，代码长度: ${testCode.length}`);
        
        // 策略1: 匹配 HWTEST_F 宏（OpenHarmony风格）
        // HWTEST_F(TestClassName, TestName, TestSize.Level0)
        const hwtestRegex = /HWTEST_F\s*\(\s*([^,]+?)\s*,\s*(\w+)\s*,\s*[^)]+\)/g;
        let match;
        let count = 0;
        
        while ((match = hwtestRegex.exec(testCode)) !== null) {
            count++;
            const testClassName = match[1].trim();
            const testName = match[2].trim();
            
            Logger.info(`[CoverageAnalyzer]      [${count}] 发现 HWTEST_F: ${testClassName}::${testName}`);
            
            // 尝试提取测试体（从HWTEST_F位置开始找到对应的大括号块）
            const bodyStartIndex = testCode.indexOf('{', match.index);
            if (bodyStartIndex >= 0) {
                const testBody = this.extractBlockContent(testCode, bodyStartIndex);
                
                // 分析测试场景
                const scenario = this.inferTestScenario(testName, testBody || '');
                const expectedBranches = this.inferCoveredBranches(testBody || '');
                
                Logger.info(`[CoverageAnalyzer]         场景: ${scenario}`);
                Logger.info(`[CoverageAnalyzer]         覆盖分支: ${expectedBranches.join(', ') || '无'}`);
                
                testCases.push({
                    name: testName,
                    scenario,
                    expectedBranches
                });
            }
        }
        
        // 策略2: 如果没找到HWTEST_F，尝试匹配 TEST_F（Google Test风格）
        if (testCases.length === 0) {
            Logger.info(`[CoverageAnalyzer]    未找到 HWTEST_F，尝试 TEST_F...`);
            const testFRegex = /TEST_F\s*\(\s*([^,]+?)\s*,\s*(\w+)\s*\)/g;
            
            while ((match = testFRegex.exec(testCode)) !== null) {
                count++;
                const testClassName = match[1].trim();
                const testName = match[2].trim();
                
                Logger.info(`[CoverageAnalyzer]      [${count}] 发现 TEST_F: ${testClassName}::${testName}`);
                
                const bodyStartIndex = testCode.indexOf('{', match.index);
                if (bodyStartIndex >= 0) {
                    const testBody = this.extractBlockContent(testCode, bodyStartIndex);
                    const scenario = this.inferTestScenario(testName, testBody || '');
                    const expectedBranches = this.inferCoveredBranches(testBody || '');
                    
                    testCases.push({
                        name: testName,
                        scenario,
                        expectedBranches
                    });
                }
            }
        }
        
        Logger.info(`[CoverageAnalyzer]    ✅ 总共找到 ${testCases.length} 个测试用例`);
        
        return testCases;
    }
    
    /**
     * 推断测试场景
     */
    private static inferTestScenario(testName: string, testBody: string): string {
        // 从测试名称推断
        if (testName.includes('Success') || testName.includes('Normal')) {
            return '正常场景';
        }
        if (testName.includes('Fail') || testName.includes('Error')) {
            return '异常场景';
        }
        if (testName.includes('Null') || testName.includes('Invalid')) {
            return '空值/无效输入';
        }
        if (testName.includes('Boundary') || testName.includes('Edge')) {
            return '边界条件';
        }
        
        // 从测试体内容推断
        if (testBody.includes('nullptr') || testBody.includes('NULL')) {
            return '空指针测试';
        }
        if (testBody.includes('EXPECT_EQ(.*false') || testBody.includes('EXPECT_FALSE')) {
            return '失败路径测试';
        }
        if (testBody.includes('EXPECT_TRUE') || testBody.includes('EXPECT_EQ(.*true')) {
            return '成功路径测试';
        }
        
        return '未知场景';
    }
    
    /**
     * 推断覆盖的分支
     */
    private static inferCoveredBranches(testBody: string): string[] {
        const branches: string[] = [];
        
        if (testBody.includes('nullptr') || testBody.includes('NULL')) {
            branches.push('空指针分支');
        }
        if (testBody.includes('EXPECT_TRUE')) {
            branches.push('true分支');
        }
        if (testBody.includes('EXPECT_FALSE')) {
            branches.push('false分支');
        }
        if (testBody.includes('EXPECT_NE')) {
            branches.push('不等分支');
        }
        
        return branches;
    }
    
    /**
     * 评估覆盖情况
     */
    private static estimateCoverage(
        functionBody: string,
        branches: BranchInfo[],
        testCases: TestCaseInfo[]
    ): { coveredLines: number; coveredBranches: number } {
        
        // 简化评估：基于测试用例数量和类型
        const totalTestCases = testCases.length;
        const executableLines = this.analyzeExecutableLines(functionBody);
        
        // 行覆盖率估算：
        // - 如果有测试用例，至少覆盖主路径（约50%）
        // - 每增加一个测试用例，增加约20%的覆盖
        let lineCoveragePercent = totalTestCases > 0 ? 0.5 : 0;
        // 🐛 修复：避免负数覆盖率（当 testCases = 0 时，(0-1)*0.2 = -0.2）
        if (totalTestCases > 1) {
            lineCoveragePercent += Math.min((totalTestCases - 1) * 0.2, 0.5);
        }
        const coveredLines = Math.round(executableLines * lineCoveragePercent);
        
        // 分支覆盖率估算：
        // - 正常场景：覆盖true分支
        // - 异常场景：覆盖false/error分支
        // - 边界场景：覆盖特殊分支
        let coveredBranchCount = 0;
        
        for (const branch of branches) {
            for (const testCase of testCases) {
                if (testCase.scenario.includes('正常') && branch.type === 'if') {
                    branch.covered = true;
                    coveredBranchCount++;
                    break;
                }
                if (testCase.scenario.includes('异常') && branch.type === 'else') {
                    branch.covered = true;
                    coveredBranchCount++;
                    break;
                }
            }
        }
        
        // 如果有多个测试用例，假设覆盖了更多分支
        if (totalTestCases >= 2) {
            const targetCoverageCount = Math.min(
                Math.round(branches.length * 0.7),
                branches.length
            );
            
            // 🐛 修复：标记对应数量的分支为已覆盖
            // 先统计已经标记的分支数
            const alreadyCovered = branches.filter(b => b.covered).length;
            
            // 如果需要标记更多分支
            if (alreadyCovered < targetCoverageCount) {
                let additionalNeeded = targetCoverageCount - alreadyCovered;
                for (const branch of branches) {
                    if (additionalNeeded <= 0) {
                        break;
                    }
                    if (!branch.covered) {
                        branch.covered = true;
                        additionalNeeded--;
                    }
                }
            }
            
            // 最终覆盖数 = 实际标记的分支数
            coveredBranchCount = branches.filter(b => b.covered).length;
        }
        
        return {
            coveredLines,
            coveredBranches: coveredBranchCount
        };
    }
    
    /**
     * 识别未覆盖的场景
     */
    private static identifyUncoveredScenarios(
        branches: BranchInfo[],
        testCases: TestCaseInfo[]
    ): string[] {
        const uncovered: string[] = [];
        const scenarios = new Set(testCases.map(tc => tc.scenario));
        
        // 检查常见场景是否被覆盖
        if (!scenarios.has('空值/无效输入') && !scenarios.has('空指针测试')) {
            uncovered.push('⚠️ 缺少空指针/无效输入测试');
        }
        
        if (!scenarios.has('异常场景') && branches.some(b => b.type === 'else')) {
            uncovered.push('⚠️ 缺少异常分支测试（else路径）');
        }
        
        if (testCases.length < 2) {
            uncovered.push('⚠️ 测试用例数量较少，建议增加边界条件测试');
        }
        
        // 检查未覆盖的分支类型
        const uncoveredBranches = branches.filter(b => !b.covered);
        if (uncoveredBranches.length > 0) {
            const types = [...new Set(uncoveredBranches.map(b => b.type))];
            uncovered.push(`⚠️ 未覆盖的分支类型: ${types.join(', ')}`);
        }
        
        return uncovered;
    }
    
    /**
     * 格式化覆盖率报告为Markdown
     */
    public static formatCoverageReport(report: CoverageReport): string {
        let markdown = `## 📊 覆盖率预期分析\n\n`;
        markdown += `**函数**: \`${report.functionName}\`  \n`;
        markdown += `**文件**: \`${report.sourceFile}\`\n\n`;
        
        // 覆盖率概览
        markdown += `### 📈 覆盖率概览\n\n`;
        markdown += `| 类型 | 覆盖情况 | 百分比 | 评级 |\n`;
        markdown += `|------|----------|--------|------|\n`;
        
        const lineCoverageGrade = this.getCoverageGrade(report.lineCoverage);
        const branchCoverageGrade = this.getCoverageGrade(report.branchCoverage);
        
        markdown += `| **行覆盖** | ${report.coveredLines}/${report.totalLines} | ${report.lineCoverage.toFixed(1)}% | ${lineCoverageGrade} |\n`;
        markdown += `| **分支覆盖** | ${report.coveredBranches}/${report.totalBranches} | ${report.branchCoverage.toFixed(1)}% | ${branchCoverageGrade} |\n\n`;
        
        // 测试用例列表
        markdown += `### 🧪 测试用例 (${report.testCases.length} 个)\n\n`;
        for (const testCase of report.testCases) {
            markdown += `- **${testCase.name}**\n`;
            markdown += `  - 场景: ${testCase.scenario}\n`;
            if (testCase.expectedBranches.length > 0) {
                markdown += `  - 覆盖分支: ${testCase.expectedBranches.join(', ')}\n`;
            }
        }
        markdown += `\n`;
        
        // 分支详情
        if (report.branches.length > 0) {
            markdown += `### 🌳 分支详情\n\n`;
            const coveredBranches = report.branches.filter(b => b.covered);
            const uncoveredBranches = report.branches.filter(b => !b.covered);
            
            markdown += `**已覆盖** (${coveredBranches.length}/${report.branches.length}):\n`;
            for (const branch of coveredBranches) {
                markdown += `- ✅ ${branch.type} (${branch.location})`;
                if (branch.condition) {
                    markdown += ` - \`${branch.condition}\``;
                }
                markdown += `\n`;
            }
            
            if (uncoveredBranches.length > 0) {
                markdown += `\n**未覆盖** (${uncoveredBranches.length}):\n\n`;
                markdown += `<table style="border-collapse: collapse; width: 100%; border: 2px solid #ddd;">\n`;
                markdown += `<thead>\n`;
                markdown += `<tr style="background-color: #f2f2f2;">\n`;
                markdown += `<th style="border: 1px solid #ddd; padding: 12px 8px; text-align: left; font-weight: bold;">未覆盖片段</th>\n`;
                markdown += `<th style="border: 1px solid #ddd; padding: 12px 8px; text-align: left; font-weight: bold;">未覆盖原因</th>\n`;
                markdown += `</tr>\n`;
                markdown += `</thead>\n`;
                markdown += `<tbody>\n`;
                
                for (const branch of uncoveredBranches) {
                    const branchType = branch.type;
                    
                    // 提取行号并格式化代码片段
                    let formattedSnippet = '';
                    if (branch.condition) {
                        // 从 location 中提取行号（格式如 "Line 123" 或 "line 123"）
                        const lineMatch = branch.location.match(/line\s+(\d+)/i);
                        const lineNumber = lineMatch ? lineMatch[1] : '';
                        
                        if (lineNumber) {
                            // 格式：Line 5: if (condition)
                            formattedSnippet = `<code>Line ${lineNumber}: ${branchType} (${branch.condition})</code>`;
                        } else {
                            formattedSnippet = `<code>${branchType} (${branch.condition})</code>`;
                        }
                    } else {
                        formattedSnippet = `<code>${branchType}</code>`;
                    }
                    
                    // 🎯 智能推断未覆盖原因（检测是否可以通过 Mock 覆盖）
                    let reason = '';
                    const condition = branch.condition || '';
                    
                    // 检测单例模式（GetInstance）
                    if (condition.includes('::GetInstance(') || condition.includes('GetInstance()')) {
                        reason = '🎭 <strong>可通过 Mock 单例覆盖</strong>（如 MockSingleton）';
                    }
                    // 检测外部服务调用（Get...、Create...、Init...）
                    else if (condition.match(/Get\w+\(/) || condition.match(/Create\w+\(/) || condition.match(/Init\w+\(/)) {
                        reason = '🎭 <strong>可通过 Mock 外部依赖覆盖</strong>（如 MockService）';
                    }
                    // 检测返回值判断（ret != SUCCESS）
                    else if (condition.match(/ret\s*[!=]=/) || condition.match(/result\s*[!=]=/) || condition.match(/status\s*[!=]=/)) {
                        reason = '🎭 <strong>可通过 Mock 函数返回值覆盖</strong>（设置 EXPECT_CALL 返回特定值）';
                    }
                    // 检测比较操作（compare_exchange_strong 等原子操作）
                    else if (condition.includes('compare_exchange') || condition.includes('atomic')) {
                        reason = '⚙️ <strong>多线程场景测试</strong>（需模拟并发）';
                    }
                    // 检测系统调用（pthread_、fopen、read、write 等）
                    else if (condition.match(/pthread_|fopen|fread|fwrite|open\(|read\(|write\(/)) {
                        reason = '🎭 <strong>可通过 Mock 系统调用覆盖</strong>（如 gmock 的 EXPECT_CALL）';
                    }
                    // 通用分支类型判断
                    else if (branchType === 'if' || branchType === 'else') {
                        reason = '条件分支未测试';
                    } else if (branchType === 'switch' || branchType === 'case') {
                        reason = 'switch分支未测试';
                    } else if (branchType === 'for' || branchType === 'while') {
                        reason = '循环逻辑未测试';
                    } else if (branchType === 'logical') {
                        reason = '逻辑运算符短路未测试';
                    } else if (branchType === 'ternary') {
                        reason = '三元表达式未测试';
                    } else {
                        reason = '未覆盖';
                    }
                    
                    markdown += `<tr style="border-bottom: 1px solid #ddd;">\n`;
                    markdown += `<td style="border: 1px solid #ddd; padding: 10px 8px;">${formattedSnippet}</td>\n`;
                    markdown += `<td style="border: 1px solid #ddd; padding: 10px 8px;">${reason}</td>\n`;
                    markdown += `</tr>\n`;
                }
                
                markdown += `</tbody>\n`;
                markdown += `</table>\n\n`;
            }
            markdown += `\n`;
        }
        
        // 改进建议
        if (report.uncoveredScenarios.length > 0) {
            markdown += `### 💡 改进建议\n\n`;
            for (const scenario of report.uncoveredScenarios) {
                markdown += `${scenario}\n\n`;
            }
        }
        
        // 总体评价
        markdown += `### 🎯 总体评价\n\n`;
        const avgCoverage = (report.lineCoverage + report.branchCoverage) / 2;
        if (avgCoverage >= 80) {
            markdown += `✅ **优秀** - 测试覆盖率很好，代码质量有保障！\n`;
        } else if (avgCoverage >= 60) {
            markdown += `⚠️ **良好** - 测试覆盖率尚可，建议补充更多测试用例。\n`;
        } else {
            markdown += `❌ **需要改进** - 测试覆盖率较低，强烈建议增加测试用例。\n`;
        }
        
        return markdown;
    }
    
    /**
     * 获取覆盖率评级
     */
    private static getCoverageGrade(coverage: number): string {
        if (coverage >= 90) return '🟢 优秀';
        if (coverage >= 80) return '🟢 良好';
        if (coverage >= 70) return '🟡 中等';
        if (coverage >= 60) return '🟡 及格';
        return '🔴 不足';
    }
    
    /**
     * 创建空报告
     */
    private static createEmptyReport(functionName: string, sourceFile: string): CoverageReport {
        return {
            functionName,
            sourceFile,
            totalLines: 0,
            coveredLines: 0,
            lineCoverage: 0,
            totalBranches: 0,
            coveredBranches: 0,
            branchCoverage: 0,
            branches: [],
            uncoveredScenarios: [],
            testCases: []
        };
    }
}

